package com.strongbj.iot.devices.smarrack.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

import com.strongbj.core.message.IMessageFactory;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.smarrack.message.SmarRackMessage;
import com.strongbj.iot.devices.smarrack.message.SmarRackMessageFactory;

/**
 * 带应答的处理
 * @author root
 *
 */
abstract class WithResponseHandle  implements IMessageHandle<SmarRackMessage,Object> {
	private static Logger logger = LogManager.getLogger(WithResponseHandle.class.getName());
	private static IMessageFactory<SmarRackMessage,byte[]> factory = new SmarRackMessageFactory();
	
	@Override
	public Object handle(ChannelHandlerContext ctx, SmarRackMessage t) {
		
		try {
			byte[] msg = factory.parse(t);
			final String hex = ByteUtil.byteArrToHexString(msg);
			
			ByteBuf bs = Unpooled.copiedBuffer(msg);
			ChannelFuture cf = ctx.channel().writeAndFlush(bs);
			cf.addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					logger.debug("应答自动回复成功 回复内容：{}",hex);
				}
			
			});
			
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		this.messageHandle(ctx, t);
		return null;
	}
	
	abstract void messageHandle(ChannelHandlerContext ctx, SmarRackMessage t);
}
